from flask import jsonify
from flask.views import MethodView
from app.models.user import User
from ..auth import generate_token
from ..forms import TokenForm
from app.extensions import db
import requests
import json


class AuthTokenAPI(MethodView):
    def post(self):
        form = TokenForm()
        if form.validate_on_submit():
            grant_type = form.grant_type.data
            username = form.username.data
            password = form.password.data

            if grant_type is None or grant_type.lower() != 'password':
                return jsonify(success=False, message='失败的token')

            if not username or not password:
                return jsonify(success=False, message='账号或密码不能为空')

            res = requests.get('http://user.apiary.com.cn/v1/user/authorize?login={}&password={}'.format(username, password))
            data = json.loads(res.text)
            if data['success'] is False:
                return jsonify(success=False, message=data['data']['message'])

            user = User.query.filter_by(username=username).first()

            if user is None:
                user = User(username=username, status=100)
                db.session.add(user)
                db.session.commit()

            if user.status != 100:
                return jsonify(success=False, message="账号未审核！")

            token, expiration = generate_token(user)

            response = jsonify({
                'success': True,
                'data': {
                    'access_token': token,
                    'expiration': expiration
                }
            })
            response.headers['Cache-Control'] = 'no-store'
            response.headers['Pragma'] = 'no-cache'
            return response

        if form.errors:
            message = {i[0]: i[1][0] for i in form.errors.items()},
            return jsonify(success=False, message=message)
